﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Globalization;
using Microsoft.Extensions.Configuration;

namespace LogLib
{
    public class LogConfig
    {
        #region static fields
        static LogConfig()
        {
            string id = "China Standard Time";
            localZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(id);
        }

        /// <summary>
        public static IFormatProvider Ifp = new CultureInfo("zh-CN", true);

        /// <summary>
        /// 当前日期
        /// </summary>
        private static DateTime _nowDate = DateTime.MinValue;

        private static TimeZoneInfo localZoneInfo = null;   

        private static LogConfig Instance;

        public static LogConfig Get()
        {
            if (Instance != null)
            {
                return Instance;
            }
            Instance = new ConfigurationBuilder()
                .AddIniFile(".\\LogConfig.ini")
                .Build()
                .Get<LogConfig>();
            Instance.Check();
            return Instance;
        }

        public static DateTime Now()
        {
            return TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, localZoneInfo);
        }
        #endregion

        /// <summary>
        /// 同步写锁
        /// </summary>
        private object lockflag = new object();

        /// <summary>
        /// 当前的默认日记保存目录
        /// </summary>
        private string _todayDirectory = "";

        public LogOption LogSetting { get; set; } = new LogOption();

        public string TodayDirectory
        {
            get { return _todayDirectory; }
        }

        public LogConfig()
        {
            _nowDate = DateTime.Now.Date;
        }

        private void CheckAndSetDiskName(ref string path)
        {
            bool available = false;
            path = path.Trim();
            string diskName = path.Substring(0, 1);
            diskName = diskName.ToUpper();
            DriveInfo[] allDirves = DriveInfo.GetDrives();
            for (int i = 0; i < allDirves.Length; i++)
            {
                string name = allDirves[i].Name.Substring(0, 1);
                if (diskName.Equals(name.ToUpper()))
                {
                    if (allDirves[i].IsReady)
                    {
                        available = true;
                        break;
                    }
                }
            }
            if (!available)
            {
                for (int i = 0; i < allDirves.Length; i++)
                {
                    if (allDirves[i].IsReady)
                    {
                        path = allDirves[i].Name + "Log\\";
                        break;
                    }
                }
            }
        }

        public bool Check()
        {
            string path = LogSetting.BaseDirectory;
            Console.WriteLine($"BaseDirectory:{path}");         
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                CheckAndSetDiskName(ref path);
            }                    
            if (!Directory.Exists(path))
            {
                try
                {
                    Directory.CreateDirectory(path);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("试图创建目录{0}失败，原因: {1}.\n请检查配置文件的配置是否正确.", path, ex.Message);
                    return false;
                }
            }      
            if(!Directory.Exists(path))
            {
                LogSetting.SetDefaultBaseDirectory();
            }
            CheckLogFolder();
            return true;
        }

        /// <summary>
        /// 检查当天的文件夹是否创建
        /// </summary>
        public void CheckLogFolder()
        {
            DateTime currentTime = Now();
            if (!_nowDate.Equals(currentTime.Date) || string.IsNullOrEmpty(_todayDirectory))
            {
                _nowDate = currentTime.Date;
                _todayDirectory = string.Format(@"{0}\{1}\{2}",
                    LogSetting.BaseDirectory, currentTime.ToString("yyyyMM", Ifp),
                    currentTime.ToString("dd", Ifp));
                Log.UpdateHashtableData();
            }
            if (!Directory.Exists(_todayDirectory))
            {
                Directory.CreateDirectory(_todayDirectory);
            }
        }
    }
}
